import java.io.*;
public class FileSplitter {

    private int size;

    private FileSplitter() {
        super();
    }

    public static FileSplitter getInstance(int size) {
        FileSplitter fs = new FileSplitter();
        fs.size = size;
        return fs;
    }

    public int split(File origin, File destination)  throws IOException{
        FileSplitter fs = FileSplitter.getInstance(size);
        long bsize = origin.length();
        String name = origin.getName();
        String prefix = "";
        String suffix = "";
        int index = name.indexOf(".");
        if (index > 0) {
            prefix = name.substring(0, index);
            suffix = name.substring(index);
        } else {
            prefix = name;
        }
        long n = bsize / fs.size;
        if (bsize % fs.size != 0) {
            n++;
        }
        InputStream in = new FileInputStream(origin);
        final byte[] bytes = new byte[size];

        for( int i = 1 ; i <= n ; i++ ) {
            String filename = prefix + "#" + ( i < 10 ? ( "0" + i ) : i ) + suffix ;

            int x = in.read( bytes ); // 从 字节输入流 中读取数据到 bytes 数组中并返回实际读取到的有效字节数

            File dest = new File( destination , filename );
            OutputStream out = new FileOutputStream( dest );
            out.write( bytes ,  0 , x ); // 将 bytes 数组中 [ 0 , x ) 之间的字节写入到输出流中
            out.close();
        }

        in.close();
        return (int) n;
    }
    public static void main( String[] args ) throws IOException {

        File origin = new File( "D:/迅雷下载/photo.jpg" ) ;
        File dest = new File( "D:/迅雷下载/" ) ;

        int size = 1 << 20 ;

        FileSplitter fs = FileSplitter.getInstance( size );

        int n = fs.split( origin , dest );
        System.out.println( "拆分后的文件数目为: " + n );
    }
}


